import { useCallback, useEffect, useMemo, useState } from 'react'
import { throttle } from 'lodash'
import { Select, SelectProps } from 'antd'

import { DEFAULT_PAGE_SIZE } from '@/utils/pagination'
import { apiGetEventTemplateList } from '@oBiz/TrackManage/EventTemplate/apis'
import { IEventTemplateODTO } from '@oBiz/TrackManage/EventTemplate/interface'

interface IEventTemplateSelectOption extends IEventTemplateODTO {
  label: string
  value: number | string
}

export const EventTemplateSelect = (props: SelectProps) => {
  const [options, setOptions] = useState<IEventTemplateSelectOption[]>([])

  // 持久化：避免每次渲染都新建函数
  const getTemplateList = useCallback(async ({ searchWord = undefined }: { searchWord?: string }) => {
    const data = await apiGetEventTemplateList({
      page: 1,
      size: DEFAULT_PAGE_SIZE,
      searchWord,
    })
    setOptions(
      data?.records?.map(item => ({
        label: item.templateCn || '',
        value: item.eventTemplateId || '',
        ...item,
      })) || [],
    )
  }, [])

  // 只创建一次节流函数实例
  const onSearch = useMemo(
    () =>
      throttle(
        (value: string) => {
          getTemplateList({ searchWord: value })
        },
        500,
        { leading: false, trailing: true },
      ),
    [getTemplateList],
  )

  // 组件卸载时取消可能的 trailing 调用
  useEffect(() => () => onSearch.cancel(), [onSearch])

  useEffect(() => {
    getTemplateList({})
  }, [getTemplateList])

  return (
    <Select
      {...props}
      options={options}
      showSearch
      optionFilterProp="label"
      filterOption={(input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
      onSearch={onSearch}
    />
  )
}
